package ru.ipccenter.belovseregas.world;

import java.util.ArrayList;
import ru.ipccenter.belovseregas.robot.Robot;
import ru.ipccenter.belovseregas.point.Point;

public class World {
	int n;
	int m;
	private ArrayList<Robot> robots;
	private ArrayList<Point> points;
	
	public World() {
		n = 0;
		m = 0;
		robots = new ArrayList<Robot>();
		points = new ArrayList<Point>();
	}
	
	public World(int n , int m) {
		int i, j;
		
		this.n = n;
		this.m = m;
		robots = new ArrayList<Robot>();
		points = new ArrayList<Point>(m * n);	
		
		for(i = 0; i < n; i++) {
			for (j = 0; j < m; j++) {
				points.add(new Point(this, j, i));
			}
		}
	}

	public int getN() {
		return n;
	}

	public void setN(int n) {
		this.n = n;
	}

	public int getM() {
		return m;
	}

	public void setM(int m) {
		this.m = m;
	}

	public ArrayList<Robot> getRobots() {
		return robots;
	}
	

	public void setRobots(ArrayList<Robot> robots) {
		this.robots = robots;
	}
	
	public Robot getRobot(int index) {
		return robots.get(index);
	}

	public ArrayList<Point> getPoints() {
		return points;
	}

	public void setPoints(ArrayList<Point> points) {
		this.points = points;
	}
	
	public Point getPoint(int x, int y) {
		return points.get(n * y + x);
	}
	
	public void putRobot(int x, int y) {
		Robot r = new Robot(this, x, y);
		robots.add(r);
		this.points.get(n * y + x).addRobot(r);
	}
	
	public void delRobot(Robot robot) {
		if(robot.getPoint()!= null) {
			robot.getPoint().delRobot(robot);
		}
		robots.remove(robot);
	}
	
	public int robotNumber() {
		return robots.size();
	}
	
	public void doStep() {
		int i;
		for (i = 0; i < robots.size(); i++) {
			robots.get(i).move();
		}
	}
	
	public void crashIllegalRobots() {
		int i;
		for (i = 0; i < robots.size(); i++) {
			if (robots.get(i).getPoint() == null) {
				delRobot(robots.get(i));
				i--;
			}
		}
		
		for(i = 0; i < points.size(); i++) {
			if (points.get(i).robotsNumber() > 1) {
				points.get(i).delAllRobots();
			}
		}
	}
	
	public void printWorld() {
		int i;
		for (i = 0; i < points.size(); i++) {
			if (i % n == 0) {
				System.out.println();
			}
			System.out.print(points.get(i).robotsNumber());
		}
		System.out.println();
	}
	
	
	
	

	
	

}
